//
//  CompressionView.swift
//  ZipTool
//
//  Created by jerry on 2025/9/14.
//

import SwiftUI
import UniformTypeIdentifiers

struct CompressionView: View {
    @StateObject private var compressionManager = CompressionManager()
    @State private var selectedFormat: CompressionFormat = .zip
    @State private var isTargeted = false
    @State private var showingFilePicker = false
    @State private var showingSavePanel = false
    @State private var showingSuccessAlert = false
    @State private var compressionProgress: Double = 0
    
    var body: some View {
        VStack(spacing: 0) {
            if !compressionManager.items.isEmpty {
                // 压缩项目列表
                compressionItemsView
                
                Spacer()
                
                // 压缩设置和按钮
                compressionControlsView
            } else {
                // 空白界面，显示拖拽区域
                emptyDropZone
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .padding()
        .navigationTitle("压缩工具")
        .alert("错误", isPresented: .constant(compressionManager.errorMessage != nil)) {
            Button("确定") {
                compressionManager.errorMessage = nil
            }
        } message: {
            Text(compressionManager.errorMessage ?? "")
        }
        .alert("压缩完成", isPresented: $showingSuccessAlert) {
            Button("确定") { }
        } message: {
            Text("文件已成功压缩到指定位置")
        }
        .fileImporter(
            isPresented: $showingFilePicker,
            allowedContentTypes: [.item],
            allowsMultipleSelection: true
        ) { result in
            switch result {
            case .success(let urls):
                compressionManager.addItems(urls: urls)
            case .failure(let error):
                compressionManager.errorMessage = "选择文件失败: \(error.localizedDescription)"
            }
        }
        .onReceive(NotificationCenter.default.publisher(for: .newArchive)) { _ in
            showingFilePicker = true
        }
    }
    
    // MARK: - 视图组件
    
    private var emptyDropZone: some View {
        Button(action: {
            showingFilePicker = true
        }) {
            ZStack {
                Color.clear
                
                VStack(spacing: 16) {
                    RoundedRectangle(cornerRadius: 12)
                        .fill(isTargeted ? Color.green.opacity(0.2) : Color.gray.opacity(0.1))
                        .stroke(
                            isTargeted ? Color.green : Color.gray.opacity(0.3),
                            style: StrokeStyle(lineWidth: 2, dash: [10])
                        )
                        .frame(width: 200, height: 200)
                        .overlay {
                            VStack(spacing: 12) {
                                Image(systemName: "plus.rectangle.on.folder")
                                    .font(.system(size: 48))
                                    .foregroundColor(isTargeted ? .green : .gray)
                                
                                Text(isTargeted ? "释放文件以添加" : "添加文件或文件夹")
                                    .font(.headline)
                                    .foregroundColor(isTargeted ? .green : .gray)
                                
                                Text("或拖拽文件到此处")
                                    .font(.subheadline)
                                    .foregroundColor(.secondary)
                                
                                Text("支持创建 ZIP、TAR、TAR.GZ 格式")
                                    .font(.caption)
                                    .foregroundColor(.secondary)
                            }
                            .padding()
                        }
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity)
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .contentShape(Rectangle())
        }
        .buttonStyle(PlainButtonStyle())
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .onDrop(of: [.fileURL], isTargeted: $isTargeted) { providers in
            let urls = providers.compactMap { provider in
                var url: URL?
                let semaphore = DispatchSemaphore(value: 0)
                
                provider.loadItem(forTypeIdentifier: UTType.fileURL.identifier, options: nil) { data, error in
                    if let data = data as? Data {
                        url = URL(dataRepresentation: data, relativeTo: nil)
                    }
                    semaphore.signal()
                }
                
                semaphore.wait()
                return url
            }
            
            if !urls.isEmpty {
                compressionManager.addItems(urls: urls)
                return true
            }
            return false
        }
    }
    
    private var compressionItemsView: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack {
                Text("待压缩项目")
                    .font(.headline)
                Spacer()
                Text("\(compressionManager.fileCount) 个文件, \(compressionManager.directoryCount) 个文件夹")
                    .font(.caption)
                    .foregroundColor(.secondary)
            }
            
            HStack {
                Text("总大小: \(FileTypeHelper.formatFileSize(compressionManager.totalSize))")
                    .font(.caption)
                    .foregroundColor(.secondary)
                
                Spacer()
                
                Button("清空列表") {
                    compressionManager.clearAll()
                }
                .font(.caption)
                
                Button("添加更多") {
                    showingFilePicker = true
                }
                .font(.caption)
            }
            
            List {
                ForEach(Array(compressionManager.items.enumerated()), id: \.offset) { index, item in
                    HStack {
                        Image(systemName: item.isDirectory ? "folder.fill" : "doc.fill")
                            .foregroundColor(item.isDirectory ? .blue : .gray)
                            .frame(width: 20)
                        
                        VStack(alignment: .leading, spacing: 2) {
                            Text(item.relativePath)
                                .font(.system(.body, design: .monospaced))
                            
                            if !item.isDirectory {
                                Text(FileTypeHelper.formatFileSize(item.size))
                                    .font(.caption)
                                    .foregroundColor(.secondary)
                            }
                        }
                        
                        Spacer()
                        
                        Button(action: {
                            compressionManager.removeItem(at: index)
                        }) {
                            Image(systemName: "minus.circle.fill")
                                .foregroundColor(.red)
                        }
                        .buttonStyle(PlainButtonStyle())
                    }
                    .padding(.vertical, 2)
                }
            }
            .listStyle(PlainListStyle())
            .frame(maxHeight: 300)
        }
    }
    
    private var compressionControlsView: some View {
        VStack(spacing: 12) {
            HStack {
                Text("压缩格式:")
                    .font(.headline)
                
                Picker("格式", selection: $selectedFormat) {
                    ForEach(CompressionFormat.allCases, id: \.self) { format in
                        Text(format.displayName).tag(format)
                    }
                }
                .pickerStyle(SegmentedPickerStyle())
            }
            
            if compressionManager.isCompressing {
                VStack(spacing: 8) {
                    ProgressView(value: compressionProgress)
                        .progressViewStyle(LinearProgressViewStyle())
                    
                    Text("压缩中... \(Int(compressionProgress * 100))%")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
            }
            
            Button(action: {
                showSavePanel()
            }) {
                HStack {
                    Image(systemName: "archivebox.fill")
                    Text("创建压缩包")
                }
                .font(.headline)
                .foregroundColor(.white)
                .frame(maxWidth: .infinity)
                .padding()
                .background(Color.green)
                .cornerRadius(10)
            }
            .disabled(compressionManager.isCompressing || compressionManager.items.isEmpty)
        }
    }
    
    // MARK: - 方法
    
    private func showSavePanel() {
        let panel = NSSavePanel()
        panel.allowedContentTypes = [UTType(filenameExtension: selectedFormat.fileExtension)!]
        panel.nameFieldStringValue = "Archive.\(selectedFormat.fileExtension)"
        panel.title = "保存压缩包"
        
        if panel.runModal() == .OK, let url = panel.url {
            compressionProgress = 0
            compressionManager.createArchive(at: url, format: selectedFormat) { progress in
                compressionProgress = progress
                
                if progress >= 1.0 {
                    showingSuccessAlert = true
                }
            }
        }
    }
}

#Preview {
    CompressionView()
}